package com.rainbow.service

import com.fasterxml.jackson.databind.ObjectMapper
import com.rainbow.entity.Weather
import com.rainbow.entity.WeatherResponse
import org.springframework.beans.factory.annotation.Autowired
import org.springframework.http.ResponseEntity
import org.springframework.stereotype.Service
import org.springframework.web.client.RestTemplate

@Service
class WeatherDataService {

    @Autowired
    private lateinit var restTemplate: RestTemplate

    private var WEATHER_API = "http://wthrcdn.etouch.cn/weather_mini"

    fun getDataByCityId(cityId: String): WeatherResponse? {
        val uri = WEATHER_API + "?cityId=" + cityId

        return this.doGetWeatherData(uri)
    }

    fun getDataByCityName(cityName: String): WeatherResponse? {
        val uri = WEATHER_API + "?city=" + cityName

        return this.doGetWeatherData(uri)
    }

    fun doGetWeatherData(uri: String): WeatherResponse? {
        val response = restTemplate.getForEntity(uri, String::class.java) as ResponseEntity<String>

        var strBody = ""
        if (response.statusCodeValue == 200) {
            strBody = response.body
        }
        val mapper = ObjectMapper()

        var weather: WeatherResponse? = null

        try {
            weather = mapper.readValue(strBody, WeatherResponse::class.java)
        } catch (e: Exception) {
            e.printStackTrace()
        }
        return weather
    }
}